package sample.client;

import java.util.ArrayList;

import sample.shared.Consts;
import sample.shared.result.Client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor.Path;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.cell.core.client.form.ComboBoxCell.TriggerAction;
import com.sencha.gxt.data.shared.LabelProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.widget.core.client.form.ComboBox;
import com.sencha.gxt.widget.core.client.info.Info;

public class ClientList
{
  private ArrayList<ListStore<Client>> stores =
      new ArrayList<ListStore<Client>>();

  interface ClientProperties extends PropertyAccess<Client>
  {
    @Path("code")
    ModelKeyProvider<Client> key();

    LabelProvider<Client> name();
  }

  public static ComboBox<Client> createClientCombo() {
    ClientProperties props = GWT.create(ClientProperties.class);

    ListStore<Client> clients = new ListStore<Client>(props.key());
    instance.stores.add(clients);
    ComboBox<Client> searchClientCombo =
        new ComboBox<Client>(clients, new LabelProvider<Client>() {
          @Override
          public String getLabel(Client client) {
            return client.getName() + " ["+ client.getCode() + "]";
          }
        });

    searchClientCombo.setTypeAhead(true);
    searchClientCombo.setForceSelection(true);
    searchClientCombo.setEmptyText("Enter client name...");
    searchClientCombo.setTriggerAction(TriggerAction.ALL);
    searchClientCombo.setWidth(350);

    return searchClientCombo;
  }

  private static ClientList instance = new ClientList();

  public static ClientList get() {
    return instance;
  }

  private final ClientManagerServiceAsync cmService = GWT
      .create(ClientManagerService.class);

  public ClientList() {
    update();
  }

  public void update() {
    cmService.getAllClients(new AsyncCallback<ArrayList<Client>>() {
      @Override
      public void onFailure(Throwable caught) {
        Info.display("Error", "Failed to obtain client list" + Consts.NEWLINE
            + caught.getMessage());
      }

      @Override
      public void onSuccess(ArrayList<Client> result) {
        for (ListStore<Client> store : stores) {
          store.clear();
          store.addAll(result);
        }
      }
    });
  }
}
